﻿/*
 * Created by SharpDevelop.
 * User: fred
 * Date: 29/03/2011
 * Time: 20:33
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using MetaVideoEditorEvolved.Entity;
using MetaVideoEditorEvolved.ViewModel;
using mveEngine;

namespace MetaVideoEditorEvolved.Helper
{
	/// <summary>
	/// Description of CreateMediaFolderHelper.
	/// </summary>
	public class CreateMediaFolderHelper
	{
		private DirectoryInfo di;
		private readonly Regex[] episodeExpressions = new Regex[] {
			new Regex(@"(?<seriesname>[^\\]*)([s|S])(?<seasonnumber>\d{2,3})(([x|X]|[e|E])|([x|X][e|E]))(?<epnumber>\d{1,3})[^\\]*$", RegexOptions.Compiled), // S01E02 blah.avi, S01xE01 blah.avi
			new Regex(@"(?<seriesname>[^\\]*)([s|S])aison\s(?<seasonnumber>\d{2,3}).*([e|E])pisode\s(?<epnumber>\d{1,3})", RegexOptions.Compiled)
		};
		
		public CreateMediaFolderHelper(string path)
		{
			di = new DirectoryInfo(path);
		}
		
		public List<CreateMediaFolderItem> GetMediaFolder()
		{
			List<CreateMediaFolderItem> items = new List<CreateMediaFolderItem>();
			
			foreach (var extension in Kernel.Instance.ConfigData.FilmExtension.Split(','))
			{
				FileInfo[] rgFiles = di.GetFiles("*" + extension);
				
				foreach (var files in rgFiles)
				{
					items.Add(new CreateMediaFolderItem
					          {
					          	Status = ActionStatus.InProgress,
					          	Media = files
					          });
				}
			}
			
			return items;
		}
		
		public void CreateMediaFolder(CreateMediaFolderItem media)
		{
			EpisodeInformation episodeInformation = Episode(media.Media.Name.Replace(media.Media.Extension, string.Empty));
			
			try
			{
				if(episodeInformation==null)
				{
					string pathDirectory = media.Media.FullName.Replace(media.Media.Extension, string.Empty);
					Directory.CreateDirectory(pathDirectory);
					
					FileInfo[] mediaFiles = di.GetFiles(media.Media.Name.Replace(media.Media.Extension, string.Empty) + ".*");
					FileInfo[] fanartFiles = di.GetFiles(media.Media.Name.Replace(media.Media.Extension, string.Empty) + "-fanart.*");
					
					foreach (var file in mediaFiles)
					{
						if(File.Exists(Path.Combine(pathDirectory, file.Name)))
						{
							File.Delete(Path.Combine(pathDirectory, file.Name));
						}
						
						File.Move(file.FullName, pathDirectory  + "\\" + file.Name);
					}
					
					foreach (var fanart in fanartFiles) {
						if(File.Exists(Path.Combine(pathDirectory, fanart.Name)))
						{
							File.Delete(Path.Combine(pathDirectory, fanart.Name));
						}
						
						File.Move(fanart.FullName, pathDirectory  + "\\" + fanart.Name);
					}
					
					media.Status = ActionStatus.Success;
				}
				else
				{
					DirectoryInfo di = 	media.Media.Directory;
					
					var serieDirectory = Path.Combine(di.FullName, episodeInformation.SerieName);
					var seasonDirectory = Path.Combine(di.FullName, episodeInformation.SerieName, "Saison " + episodeInformation.SeasonNumber.TrimStart('0'));
					
					if(!Directory.Exists(serieDirectory))
					{
						Directory.CreateDirectory(serieDirectory);
					}
					
					if(!Directory.Exists(seasonDirectory))
					{
						Directory.CreateDirectory(seasonDirectory);
					}
					
					File.Move(media.Media.FullName, Path.Combine(seasonDirectory, media.Media.Name));
					
					media.Status = ActionStatus.Success;
				}
			}
			catch(Exception ex)
			{
				Tracer.TracerInstance.TraceError("Exception in CreateMediaFolderHelper", ex);
				throw;
			}
		}
		
		private EpisodeInformation Episode(string name)
		{
			foreach (Regex r in episodeExpressions)
			{
				Match m = r.Match(name);
				
				if (m.Success)
				{
					return new EpisodeInformation
					{
						EpisodeNumber = m.Groups["epnumber"].Value,
						SeasonNumber = m.Groups["seasonnumber"].Value,
						SerieName = m.Groups["seriesname"].Value
					};
				}
			}
			
			return null;
		}
		
		class EpisodeInformation
		{
			public string EpisodeNumber { get; set; }
			
			public string SeasonNumber { get; set; }
			
			public string SerieName { get; set; }
		}
	}
}
